package com.qezhhnjy.cloud.common.pool.factory;

import com.qezhhnjy.cloud.common.pool.conn.Conn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * @author zhaoyangfu - 2020/8/20 15:22
 */
@Slf4j
public class PoolFactory extends BasePooledObjectFactory<Conn> {

    private static int count = 1;

    @Override
    public Conn create() throws Exception {
        return new Conn(count++, "conn");
    }

    @Override
    public PooledObject<Conn> wrap(Conn conn) {
        DefaultPooledObject<Conn> object = new DefaultPooledObject<>(conn);
        log.info("wrap=>object state=>{},id=>{}", object.getState(), conn.getId());
        return object;
    }

    @Override
    public void destroyObject(PooledObject<Conn> p) throws Exception {
        super.destroyObject(p);
        log.info("destroy=>object state=>{},id=>{}", p.getState(), p.getObject().getId());
    }

    @Override
    public boolean validateObject(PooledObject<Conn> p) {
        log.info("validate=>object state=>{},id=>{}", p.getState(), p.getObject().getId());
        return true;
    }

    @Override
    public void activateObject(PooledObject<Conn> p) throws Exception {
        log.info("activate=>object state=>{},id=>{}", p.getState(), p.getObject().getId());
        super.activateObject(p);
        log.info("activate=>object state=>{},id=>{}", p.getState(), p.getObject().getId());
    }

    @Override
    public void passivateObject(PooledObject<Conn> p) throws Exception {
        super.passivateObject(p);
        log.info("passivate=>object state=>{},id=>{}", p.getState(), p.getObject().getId());
    }
}
